package com.example.buletooth_spp;

import static com.example.buletooth_spp.BluetoothDataPack.FRAME_HEADER;
import static com.example.buletooth_spp.BluetoothDataPack.MAX_DATA_LENGTH;

import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.Arrays;


public class BlueToothStream extends BlueToothSelectTools{

    private RecDataFrame frame;
    Thread thread;

    public BlueToothStream(AppCompatActivity activity) {
        super(activity);
    }

    public void bluetoothSendData(byte[] bytes)
    {
        if(bytes == null)
            return;

        if(null == this.outputStream)
        {
            PrintTip.printInfo(this.activity, "连接还未建立，无法发送");
            return;
        }

        try {
            outputStream.write(bytes);
        } catch (IOException e) {
            PrintTip.printInfo(this.activity, "蓝牙发送数据失败，错误信息:" + e.toString());
            //throw new RuntimeException(e);
        }
    }

    private boolean isListening = false;

    private byte readByte()
    {
        byte buf[] = new byte[1];
        try {
            inputStream.read(buf);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return buf[0];
    }

    // 启动监听蓝牙数据的线程
    public void startListening(Handler handler) {
        isListening = true;
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int receiveIndex = 0;
                byte[] receiveBuffer = new byte[MAX_DATA_LENGTH + 3];  // +3 以包含帧头、长度和校验和

                while (isListening) {
                    byte b = readByte();

                    // 将接收到的字节填入缓冲区
                    receiveBuffer[receiveIndex++] = b;

                    // Step 1: 检查是否至少接收到帧头和长度
                    if (receiveIndex >= 2) {
                        // 检查帧头是否正确
                        if (receiveBuffer[0] != FRAME_HEADER) {
                            receiveIndex = 0;  // 帧头不匹配，重置缓冲区
                            continue;
                        }

                        // Step 2: 获取数据长度
                        int length = receiveBuffer[1];
                        if (length > MAX_DATA_LENGTH) {
                            receiveIndex = 0;  // 数据长度超限，重置缓冲区
                            continue;
                        }

                        // Step 3: 检查是否接收到完整帧
                        if (receiveIndex == length + 3) {  // 包含帧头、长度和校验和的总长度
                            // Step 4: 计算校验和
                            byte calculatedChecksum = 0;
                            for (int i = 2; i < length; i++) {  // 包括帧头和长度
                                calculatedChecksum += receiveBuffer[i];
                            }

                            // 获取接收到的校验和
                            int receivedChecksum = receiveBuffer[length + 2];

                            // 校验和匹配
                            if (calculatedChecksum == receivedChecksum) {
                                // 解包有效数据
                                byte[] data = new byte[length];
                                System.arraycopy(receiveBuffer, 2, data, 0, length);

                                // 通过 Handler 发送解包后的数据给主线程
                                Message msg = handler.obtainMessage(0, data);
                                handler.sendMessage(msg);
                            }

                            // 重置接收缓冲区，等待下一帧
                            receiveIndex = 0;
                        }

                        if(receiveIndex >= receiveBuffer.length)
                            receiveIndex = 0;
                    }
                }
            }
        });
        thread.start();
    }


//    public void startListening(Handler handler) {
//        isListening = true;
//            thread = new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    int receiveIndex = 0;
//                    byte receiveBuffer[] = new byte[BluetoothDataPack.MAX_DATA_LENGTH + 12];
//
//                    while (true) {
//                        byte b = readByte();
//                        receiveBuffer[receiveIndex++] = b;
//
//                        // 检查是否接收到完整的帧
//                        if (receiveIndex >= 3) { // 至少需要 3 字节：帧头、长度、校验和
//                            if (receiveBuffer[0] == BluetoothDataPack.FRAME_HEADER) {
//                                // 获取数据长度
//                                byte dataLength = receiveBuffer[1];
//
//                                // 检查数据长度是否合法
//                                if ((dataLength <= BluetoothDataPack.MAX_DATA_LENGTH))
//                                {
//                                    // 复制到解包结构体
//                                    //memcpy(&unpackedFrame, receiveBuffer, sizeof(DataFrame));
//
//                                    // 校验和验证
//                                    byte checksum = 0;
//                                    for (int i = 2; i < receiveIndex - 1; i++) {
//                                        checksum += receiveBuffer[i];
//                                    }
//
//                                    // 校验成功，即一帧数据接收完毕
//                                    if (checksum == receiveBuffer[receiveIndex - 1]) {
//                                        Message msg = handler.obtainMessage();
//                                        byte[] frame = Arrays.copyOfRange(receiveBuffer, 2, receiveIndex - 2);
//                                        msg.obj = frame;
//                                        handler.sendMessage(msg);
//                                    }
//
//                                    // 重置接收索引，准备接收下一个数据帧
//                                    receiveIndex = 0;
//                                }
//                            } else {
//                                // 如果帧头不匹配，重置接收索引
//                                receiveIndex = 0;
//                            }
//                        }
//
//                        // 如果接收缓冲区已满，重置接收索引
//                        if (receiveIndex >= receiveBuffer.length) {
//                            receiveIndex = 0;
//                        }
//                    }
//                }
//            });
//            thread.start();
//    }

    public void bluetoothSendPack(byte[] data)
    {
        this.bluetoothSendData(BluetoothDataPack.packDataFrame(data));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
